#include "openglrenderer.h"
#include "QtOpenGL/QtOpenGL"
#include "widgets/leveleditorview.h"

OpenGLRenderer::OpenGLRenderer()
{
}

void OpenGLRenderer::drawQuadSprite( const QImage& image, const QPointF& pos, float fAngle /*= 0*/, const QPointF& scale /*= QPointF(1.0f, 1.0f)*/, const QRect& frameRect /*= QRect()*/ )
{
	LevelModeWidgets::LevelEditorView* pOpenGLView = qobject_cast<LevelModeWidgets::LevelEditorView*>(m_GLWidget);

	pOpenGLView->bindTexture(image, GL_TEXTURE_2D);

	glPushMatrix();
	glTranslatef(pos.x(), pos.y(), 0.0f);

	drawQuad(QRectF(0.0f, 0.0f, image.width(), image.height()),
			QRectF(frameRect.left(), frameRect.top(), frameRect.width(), frameRect.height()));
	
	glPopMatrix();
}

void OpenGLRenderer::init( QPointer<QWidget> GLWidget )
{
	m_GLWidget = GLWidget;
}

void OpenGLRenderer::drawQuad( const QRectF& rect, const QRectF& frameRect )
{
	if(rect != frameRect)
	{
		float t1x = frameRect.left()/rect.width();
		float t1y = 1.0f - (frameRect.top() + frameRect.height())/rect.height();

		float t2x = (frameRect.left() + frameRect.width())/rect.width();
		float t2y = 1.0f - (frameRect.top() + frameRect.height())/rect.height();

		float t3x = (frameRect.left() + frameRect.width())/rect.width();
		float t3y = 1.0f - (frameRect.top())/rect.height();

		float t4x = (frameRect.left())/rect.width();
		float t4y = 1.0f - (frameRect.top())/rect.height();

		glBegin(GL_QUADS);

		glTexCoord2f(t1x, t1y);
		glVertex3f(-frameRect.width()/2,  -frameRect.height()/2, 0.0f);

		glTexCoord2f(t2x, t2y);
		glVertex3f( frameRect.width()/2,  -frameRect.height()/2, 0.0f);

		glTexCoord2f(t3x, t3y);
		glVertex3f( frameRect.width()/2, frameRect.height()/2, 0.0f);

		glTexCoord2f(t4x, t4y);
		glVertex3f(-frameRect.width()/2, frameRect.height()/2, 0.0f);

		glEnd();
	}
	else
	{
		glBegin(GL_QUADS);

		glTexCoord2f(0, 0);
		glVertex3f(-rect.width()/2,  -rect.height()/2, 0.0f);

		glTexCoord2f(1, 0);
		glVertex3f( rect.width()/2,  -rect.height()/2, 0.0f);

		glTexCoord2f(1, 1);
		glVertex3f( rect.width()/2, rect.height()/2, 0.0f);

		glTexCoord2f(0, 1);
		glVertex3f(-rect.width()/2, rect.height()/2, 0.0f);

		glEnd();
	}
}

OpenGLRenderer& OpenGLRenderer::instance()
{
	static OpenGLRenderer _inst;
	return _inst;
}
